<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    :width="1200"
    okText="保存"
    @register="register"
    title="数据转换"
    @visible-change="handleVisibleChange"
  >
    <div class="tag-box">
      <BasicForm @register="registerForm">
        <template #slotCode="{ model, field }">
          <codemirror
            v-model="model[field]"
            placeholder="Code gose here..."
            :style="{ height: '600px' }"
            mode="python"
            :autofocus="true"
            :autoRefresh="true"
            :indentWithTab="true"
            :spellcheck="true"
            :tabSize="2"
            :extensions="extensions"
          />
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModal } from '/@/components/Modal';
  import { Codemirror } from 'vue-codemirror';
  import { python, pythonLanguage } from '@codemirror/lang-python';
  import { oneDark } from '@codemirror/theme-one-dark';
  import { getPythonDisplay } from '/@/api/tag/index';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { getFormErrorMessage } from '/@/utils/index';

  import { onMounted, reactive, nextTick } from 'vue';

  const [register] = useModal();
  let codeHintList = reactive([]);
  const emit = defineEmits(['getCode']);
  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
  });

  let extensions = [];
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'type',
      component: 'Select',
      label: '转换类型：',
      defaultValue: '0',
      componentProps: {
        disabled: true,
        options: [
          {
            label: '固定',
            value: '0',
          },
        ],
      },
      colProps: {
        span: 10,
      },
      rules: [
        {
          required: true,
          message: '请选择转换类型',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'converterType',
      component: 'Select',
      label: '转换方式：',
      defaultValue: '0',
      componentProps: {
        options: [
          {
            label: '无',
            value: '0',
          },
          {
            label: '比例',
            value: '1',
          },
          {
            label: '脚本',
            value: '2',
          },
          {
            label: 'BCD码',
            value: '3',
          },
        ],
      },
      colProps: {
        span: 10,
      },
      rules: [
        {
          required: true,
          message: '请选择转换方式',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'scaleValue',
      component: 'InputNumber',
      label: '比例值：',
      colProps: {
        span: 20,
      },
      defaultValue: 0,
      componentProps: {
        min: 0,
      },
      ifShow: ({ values }) => {
        return +values.converterType === 1;
      },
      rules: [
        {
          required: true,
          message: '请输入比例值',
          trigger: ['change', 'blur'],
        },
      ],
    },

    {
      field: 'code',
      component: 'Input',
      label: '  ',
      slot: 'slotCode',
      labelWidth: 1,
      colProps: {
        span: 24,
      },
      ifShow: ({ values }) => {
        return +values.converterType === 2;
      },
    },
  ];
  const [registerForm, { validateFields, setFieldsValue, resetFields, clearValidate }] = useForm({
    labelWidth: 100,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  onMounted(async () => {
    codeHintList = await getPythonDisplay();
    extensions = [
      pythonLanguage.data.of({
        autocomplete: myCompletions,
      }) as never,
      python() as never,
      oneDark as never,
    ];
  });
  async function handleSubmint() {
    try {
      let res = await validateFields();
      emit('getCode', res);
    } catch (error) {
      getFormErrorMessage(error);
    }
  }
  function handleVisibleChange(visible) {
    if (visible) {
      nextTick(() => {
        let val = {
          converterType: props.info.data.ConverterType.toString(),
          scaleValue: props.info.data.ScaleValue,
          code: props.info.data.Script,
        };
        setFieldsValue(val);
        clearValidate();
      });
    } else {
      resetFields();
    }
  }

  function myCompletions(context) {
    let word = context.matchBefore(/\w*/);
    let { text } = word;
    let options = codeHintList.filter((_item: any) => _item.label.startsWith(text));

    if (!word && !context.explicit && options.length === 0) return null;

    return {
      from: word.from,
      to: word.to,

      options: options,
    };
  }
</script>

<style lang="less" scoped>
  .tag-box {
    width: 100%;
    min-height: 600px;
  }
</style>
